package com.king.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.king.common.lang.Result;
import com.king.entity.MPost;
import com.king.entity.MUserCollection;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.king.controller.BaseController;

import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author KING
 * @since 2020-09-01
 */
@Controller
@RequestMapping("/collection")
public class MUserCollectionController extends BaseController {
    /**
     * 查询文章是否收藏
     * @param pid
     * @return
     */
    @ResponseBody
    @PostMapping("/find")
    public Result find(Long pid){
        int count = mUserCollectionService.count(new QueryWrapper<MUserCollection>()
                .eq("user_id", getProfileId())
                .eq("post_id", pid)
        );

        return Result.success(MapUtil.of("collection",count>0));
    }

    @ResponseBody
    @PostMapping("/add")
    public Result add(Long pid){
        MPost post = mPostService.getById(pid);
        Assert.notNull(post,"该文章已被删除！");

        int count = mUserCollectionService.count(new QueryWrapper<MUserCollection>()
                .eq("user_id", getProfileId())
                .eq("post_id", pid)
        );
        if(count>0){
            return Result.fail("文章已收藏！");
        }

        MUserCollection collection = new MUserCollection();
        collection.setPostId(post.getId());
        collection.setPostUserId(post.getUserId());
        collection.setUserId(getProfileId());
        collection.setCreated(new Date());
        collection.setModified(new Date());
        boolean save = mUserCollectionService.save(collection);

        return save?Result.success():Result.fail("操作失败！");
    }

    @ResponseBody
    @PostMapping("/remove")
    public Result remove(Long pid){
        MPost post = mPostService.getById(pid);
        Assert.notNull(post,"该文章已被删除！");

        boolean remove = mUserCollectionService.remove(new QueryWrapper<MUserCollection>()
                .eq("user_id", getProfileId())
                .eq("post_id", pid)
        );

        return remove?Result.success():Result.fail("操作失败！");
    }
}
